package org.wangzhen.spring.event.springdemo;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.context.event.ContextRefreshedEvent;

/**
 * 层次性上下文，spring事件传播演示
 */
public class HierarchicalEventDemo {
    public static void main(String[] args) {
        // 1、创建parent context
        AnnotationConfigApplicationContext parentContext = new AnnotationConfigApplicationContext();
        parentContext.setId("parent-context");
        parentContext.register(MyTestApplicationListener.class);
        // 2、创建child context
        AnnotationConfigApplicationContext childContext = new AnnotationConfigApplicationContext();
        childContext.setId("child-context");
        childContext.register(MyTestApplicationListener.class);
        // 3、设置父parent
        childContext.setParent(parentContext);

        //4、启动spring应用上下文
        parentContext.refresh();
        childContext.refresh();

        //5、停止spring应用上下文
        childContext.close();
        parentContext.close();

        //org.springframework.context.support.AbstractApplicationContext.publishEvent(java.lang.Object, org.springframework.core.ResolvableType)
    }

    static class MyTestApplicationListener implements ApplicationListener<ApplicationContextEvent> {
        @Override
        public void onApplicationEvent(ApplicationContextEvent event) {
            System.out.printf("监听到spring上下文【id:%s】的事件%s:\n", event.getApplicationContext().getId(), event.getClass().getSimpleName());
        }
    }

    /*也可以注入ApplicationContext，判断事件的上下文对象是否是当前的上下文对象。从而进行过滤
    作者回复: 是的，在
    https://github.com/alibaba/spring-context-support/blob/master/src/main/java/com/alibaba/spring/context/OnceApplicationContextEventListener.java
    // 就是如此实现的，在 Dubbo Spring 中也有运用~*/



}
